package com.project.managementpaltform.config;

import javax.annotation.Resource;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class MethodReqLogAspect {

    @Resource
    ObjectMapper objectMapper;
    
    /**
     * 定义切入点
     * controller包下的所有方法
    */
    @Pointcut("(execution(com.project.managementpaltform.controller.*.*(..))"+
    "||@annotation(com.project.managementpaltform.config.annotation.MethodReqLogAnno)"+
    "||@wihtin(com.project.managementpaltform.config.annotation.MethodReqLogAnno))")
    public void webLog(){}

    /**
     * 在切入点前执行
     * 
    */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint)throws Throwable {
        //接收到请求，记录请求内容
        String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        String requestParam = objectMapper.writeValueAsString(joinPoint.getArgs());
        log.info("[{}#{}] <--- {}",className,methodName,requestParam);
    }

    /**
     * 在切入点后执行
     * 
    */
    @AfterReturning(returning = "result",pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object result)throws Throwable{
         //处理完请求，返回内容
         String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
         String methodName = joinPoint.getSignature().getName();
         String responseResult = objectMapper.writeValueAsString(result);
         log.info("[{}#{}] ---> {}",className,methodName,responseResult);

    }

}
